package com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.css.fxfzxczh.base.attachment.service.AttachmentInfoService;
import com.css.fxfzxczh.base.dict.service.DictService;
import com.css.fxfzxczh.common.utils.UpdateUtil;
import com.css.fxfzxczh.constants.DesDegConstants;
import com.css.fxfzxczh.constants.FxfzConstants;
import com.css.fxfzxczh.constants.XczhConstants;
import com.css.fxfzxczh.constants.YNEnum;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.entity.SamPoiData;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.queryParams.CalculateParams;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.queryParams.SamPoiDataQuaParams;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.service.SamPoiDataService;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.vo.ResultVo;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.entity.HouDam;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.entity.SamPoiHouSur;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.queryParams.SamPoiHouSurParam;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.queryParams.SamPoiHouSurQuaParams;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.repository.HouDamStaRepository;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.repository.HouseDamageRepository;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.repository.SamPoliHouSurRepository;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.service.SamPoiHouSurService;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.entity.HouDamSta;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.verify.SamPoiHouSurExcelVerifyHandler;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.vo.SamPoiHouSurCheckVo;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.vo.SamPoiHouSurExcelVo;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiHouSur.vo.SamPoiHouSurVo;
import com.css.fxfzxczh.modules.fieldWorkManage.noticeManage.param.AuditNotice;
import com.css.fxfzxczh.modules.fieldWorkManage.noticeManage.service.NoticeService;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.entity.ReportPublicField;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.repository.ReportPublicFieldRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.entity.EarEveManage;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.service.EarEveManageService;
import com.css.fxfzxczh.modules.synthesizeInfoManage.houseStructureManagement.service.HouseStructureManagementService;
import com.css.fxfzxczh.util.*;
import com.css.fxfzxczh.web.PlatformSessionContext;
import com.css.fxfzxczh.zcpt.sys.entity.SUser;
import com.css.fxfzxczh.zcpt.sys.service.SUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;

@Service
public class SamPoliHouSurServiceImpl implements SamPoiHouSurService {
    @Resource
    SamPoliHouSurRepository samPoliHouSurRepository;

    @Resource
    HouseDamageRepository houseDamageRepository;

    @Resource
    HouDamStaRepository houDamStaRepository;

    @Resource
    AttachmentInfoService attachmentInfoService;

    @Resource
    SUserService sUserService;

    @Resource
    SamPoiDataService samPoiDataService;

    @Resource
    NoticeService noticeService;

    @Resource
    DictService dictService;

    @Resource
    EarEveManageService earEveManageService;

    @Resource
    SamPoiHouSurExcelVerifyHandler samPoiHouSurExcelVerifyHandler;

    @Resource
    ReportPublicFieldRepository reportPublicFieldRepository;

    @Resource
    HouseStructureManagementService houseStructureManagementService;


    @Override
    public Map<String, Object> getPage(SamPoiHouSurQuaParams queParams, int curPage, int pageSize) {
        Map<String, Object> page = samPoliHouSurRepository.getPage(queParams, curPage, pageSize);
        /*List<SamPoiHouSurVo> rows = (List<SamPoiHouSurVo>) page.get("rows");
        for(SamPoiHouSurVo item:rows){
            if(!PlatformObjectUtils.isEmpty(item.getMacroscopicAnomaly())){
                StringBuilder macroscopicAnomaly=new StringBuilder("");
                for(int a=0;a<item.getMacroscopicAnomaly().split(",").length;a++){
                    macroscopicAnomaly.append(macroscopicAnomaly(item.getMacroscopicAnomaly().split(",")[a])).append(",");
                }
                item.setMacroscopicAnomaly(macroscopicAnomaly.substring(0,macroscopicAnomaly.length()-1).toString());
            }
            if(!PlatformObjectUtils.isEmpty(item.getGeologicHazard())){
                StringBuilder geologicHazard=new StringBuilder("");
                for(int a=0;a<item.getGeologicHazard().split(",").length;a++){
                    geologicHazard.append(geologicHazard(item.getGeologicHazard().split(",")[a])).append(",");
                }
                item.setGeologicHazard(geologicHazard.substring(0,geologicHazard.length()-1).toString());
            }
            if(!PlatformObjectUtils.isEmpty(item.getBuildingEarthquakeDescription())){
                StringBuilder buildingEarthquakeDescription=new StringBuilder("");
                for(int a=0;a<item.getBuildingEarthquakeDescription().split(",").length;a++){
                    buildingEarthquakeDescription.append(buildingEarthquakeDescription(item.getBuildingEarthquakeDescription().split(",")[a])).append(",");
                }
                item.setBuildingEarthquakeDescription(buildingEarthquakeDescription.substring(0,buildingEarthquakeDescription.length()-1).toString());
            }
        }*/
        return page;
    }

    @Override
    @Transactional
    public String save(SamPoiHouSur samPoiHouSur) {
        String userID = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userID);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String uuid = UUIDGenerator.getUUID();
        samPoiHouSur.setId(uuid);
        samPoiHouSur.setDelFlag(YNEnum.N.toString());
        samPoiHouSur.setCreateTime(new Date());
        samPoiHouSur.setCreateUser(userID);
        samPoiHouSur.setCreateUserName(sUser.getUserName());
        samPoiHouSur.setCheckStatus("0");
        samPoiHouSur.setIsDamnificationCount("1");
        /*SamPoiData byId = samPoiDataService.findById(samPoiHouSur.getXspdId());
        samPoiHouSur.setSamplingPointName(byId.getSamplingPointName());*/
        samPoiHouSur.setGeom("POINT("+samPoiHouSur.getLongitude()+" "+samPoiHouSur.getLatitude()+")");
        samPoliHouSurRepository.save(samPoiHouSur);
        samPoiHouSur.setIsDamnificationCount(YNEnum.Y.toString());
        List<HouDam> houseDamage = samPoiHouSur.getHouseDamage();
        //保存计算参数
        if (PlatformObjectUtils.isNotEmpty(houseDamage)){
            if (houseDamage.size() > 0) {
                for (HouDam item : houseDamage) {
                    item.setId(UUIDGenerator.getUUID());
                    item.setXsphdId(uuid);
                    houseDamageRepository.save(item);
                }
            }
        }

        //保存统计结果
        List<HouDamSta> statisticsResult = samPoiHouSur.getStatisticsResult();
        if (PlatformObjectUtils.isNotEmpty(statisticsResult)){
            if (statisticsResult.size() > 0) {
                for (HouDamSta item : statisticsResult) {
                    item.setId(UUIDGenerator.getUUID());
                    item.setXsphdId(uuid);
                    houDamStaRepository.save(item);
                }
            }
        }
        return samPoiHouSur.getId();
    }

    @Override
    public void exportExcel(HttpServletResponse response, SamPoiHouSurQuaParams queParams) {
        List<SamPoiHouSur> list = samPoliHouSurRepository.getSamPoiDataList(queParams);
        if (list.size() <= 0) {
            throw new RuntimeException("数据为空,无法导出！");
        }
        for (SamPoiHouSur item : list) {
            if (!PlatformObjectUtils.isEmpty(item.getMacroscopicAnomaly())) {
                StringBuilder macroscopicAnomaly = new StringBuilder("");
                for (int a = 0; a < item.getMacroscopicAnomaly().split(",").length; a++) {
                    macroscopicAnomaly.append(macroscopicAnomaly(item.getMacroscopicAnomaly().split(",")[a])).append(",");
                }
                item.setMacroscopicAnomaly(macroscopicAnomaly.substring(0, macroscopicAnomaly.length() - 1));
            }
            if (!PlatformObjectUtils.isEmpty(item.getGeologicHazard())) {
                StringBuilder geologicHazard = new StringBuilder("");
                for (int a = 0; a < item.getGeologicHazard().split(",").length; a++) {
                    geologicHazard.append(geologicHazard(item.getGeologicHazard().split(",")[a])).append(",");
                }
                item.setGeologicHazard(geologicHazard.substring(0, geologicHazard.length() - 1));
            }
            if (!PlatformObjectUtils.isEmpty(item.getBuildingEarthquakeDescription())) {
                StringBuilder buildingEarthquakeDescription = new StringBuilder("");
                for (int a = 0; a < item.getBuildingEarthquakeDescription().split(",").length; a++) {
                    buildingEarthquakeDescription.append(buildingEarthquakeDescription(item.getBuildingEarthquakeDescription().split(",")[a])).append(",");
                }
                item.setBuildingEarthquakeDescription(buildingEarthquakeDescription.substring(0, buildingEarthquakeDescription.length() - 1));
            }
        }
        try {
            EasyPoiExcelUtil.exportExcel(list, "抽样点房屋数据信息统计", "抽样点房屋数据信息", SamPoiHouSur.class, "抽样点房屋数据信息", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getsamPoiHouCode(String eventCode) {
        EarEveManage currentEvent = earEveManageService.getCurrentEvent();
        eventCode=currentEvent.getEventCode();
        StringBuilder samPoiHouCode = new StringBuilder(eventCode + "CYDFW");
        DecimalFormat decimalFormat = new DecimalFormat("000");
        String num = "";

        String maxNum = samPoliHouSurRepository.getMaxNum(samPoiHouCode.toString());
        if (PlatformObjectUtils.isEmpty(maxNum)) {
            int i = 1;
            num = decimalFormat.format(i);
        } else {
            String substring = maxNum.substring(maxNum.length()-3);
            num = decimalFormat.format(Integer.parseInt(substring) + 1);
        }
        return samPoiHouCode.append(num).toString();
    }

    @Override
    public SamPoiHouSurVo findById(String id) {
        SamPoiHouSur samPoiHouSur = samPoliHouSurRepository.findById(id);
        SamPoiHouSurVo samPoiHouSurVo = new SamPoiHouSurVo();
        UpdateUtil.copyNullProperties(samPoiHouSur, samPoiHouSurVo);
        if (PlatformObjectUtils.isNotEmpty(samPoiHouSur.getHouseTypicalDamage())) {
            samPoiHouSurVo.setHouseTypicalDamage(attachmentInfoService.queryFile(samPoiHouSur.getHouseTypicalDamage()));
        }
        if (PlatformObjectUtils.isNotEmpty(samPoiHouSur.getLargeScalePhoto())) {
            samPoiHouSurVo.setLargeScalePhoto(attachmentInfoService.queryFile(samPoiHouSur.getLargeScalePhoto()));
        }
        if (PlatformObjectUtils.isNotEmpty(samPoiHouSur.getLargeScaleVideo())) {
            samPoiHouSurVo.setLargeScaleVideo(attachmentInfoService.queryFile(samPoiHouSur.getLargeScaleVideo()));
        }
        if (PlatformObjectUtils.isNotEmpty(samPoiHouSur.getBeforeEarthquakePicture())) {
            samPoiHouSurVo.setBeforeEarthquakePicture(attachmentInfoService.queryFile(samPoiHouSur.getBeforeEarthquakePicture()));
        }
        if (PlatformObjectUtils.isNotEmpty(samPoiHouSur.getAfterEarthquakePicture())) {
            samPoiHouSurVo.setAfterEarthquakePicture(attachmentInfoService.queryFile(samPoiHouSur.getAfterEarthquakePicture()));
        }
        if (PlatformObjectUtils.isNotEmpty(samPoiHouSur.getUavAerialPhotographyOne())) {
            samPoiHouSurVo.setUavAerialPhotographyOne(attachmentInfoService.queryFile(samPoiHouSur.getUavAerialPhotographyOne()));
        }
        if (PlatformObjectUtils.isNotEmpty(samPoiHouSur.getUavAerialPhotographyTwo())) {
            samPoiHouSurVo.setUavAerialPhotographyTwo(attachmentInfoService.queryFile(samPoiHouSur.getUavAerialPhotographyTwo()));
        }
        if (PlatformObjectUtils.isNotEmpty(samPoiHouSur.getEnclosurePhoto())) {
            samPoiHouSurVo.setEnclosurePhoto(attachmentInfoService.queryFile(samPoiHouSur.getEnclosurePhoto()));
        }
        if (PlatformObjectUtils.isNotEmpty(samPoiHouSur.getEnclosureVideo())) {
            samPoiHouSurVo.setEnclosureVideo(attachmentInfoService.queryFile(samPoiHouSur.getEnclosureVideo()));
        }
        if (PlatformObjectUtils.isNotEmpty(samPoiHouSur.getEnclosureAudio())) {
            samPoiHouSurVo.setEnclosureAudio(attachmentInfoService.queryFile(samPoiHouSur.getEnclosureAudio()));
        }
        if (PlatformObjectUtils.isNotEmpty(samPoiHouSur.getEnclosureAlbum())) {
            samPoiHouSurVo.setEnclosureAlbum(attachmentInfoService.queryFile(samPoiHouSur.getEnclosureAlbum()));
        }
        List<HouDam> houseDamageList = houseDamageRepository.findByXsphdId(id);
        samPoiHouSurVo.setHouseDamage(houseDamageList);
        List<HouDamSta> staResult = this.getStaResult(id);
        samPoiHouSurVo.setStaResult(staResult);
        return samPoiHouSurVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void statistics(SamPoiDataQuaParams params) {
        houDamStaRepository.delete(params.getId());
        List<HouDam> houDamList = params.getHouDamList();
        List<HouDam> list = new ArrayList<>();
        //List<HouDamSta> returnList = new ArrayList<>();
        //获取预置的结构类型
        List<String> preStrTypeList = houseStructureManagementService.getPreStrType("预置");

        //for (int i = 0; i <= 8; i++) {
        for (int i = 0; i < preStrTypeList.size(); i++) {
            for (int o = 0; o < houDamList.size(); o++) {
                if (preStrTypeList.get(i).equals(houDamList.get(o).getStructureType())) {
                    list.add(houDamList.get(o));
                }
            }
            List<HouDam> squareMetreList = new ArrayList<>();
            List<HouDam> betweenList = new ArrayList<>();
            List<HouDam> buildingList = new ArrayList<>();
            List<HouDam> householdList = new ArrayList<>();

            for (HouDam houDam : list) {
                switch (houDam.getCompany()) {
                    case "0":
                        squareMetreList.add(houDam);
                        break;
                    case "1":
                        betweenList.add(houDam);
                        break;
                    case "2":
                        buildingList.add(houDam);
                        break;
                    case "3":
                        householdList.add(houDam);
                        break;
                }
            }


            BigInteger pmDestroy = new BigInteger("0");
            BigInteger jDestroy = new BigInteger("0");
            BigInteger dDestroy = new BigInteger("0");
            BigInteger hDestroy = new BigInteger("0");

            BigInteger pmSeriousDamage = new BigInteger("0");
            BigInteger jSeriousDamage = new BigInteger("0");
            BigInteger dSeriousDamage = new BigInteger("0");
            BigInteger hSeriousDamage = new BigInteger("0");

            BigInteger pmModerateDamage = new BigInteger("0");
            BigInteger jModerateDamage = new BigInteger("0");
            BigInteger dModerateDamage = new BigInteger("0");
            BigInteger hModerateDamage = new BigInteger("0");

            BigInteger pmMinorDamage = new BigInteger("0");
            BigInteger jMinorDamage = new BigInteger("0");
            BigInteger dMinorDamage = new BigInteger("0");
            BigInteger hMinorDamage = new BigInteger("0");

            BigInteger pmBasicallyIntact = new BigInteger("0");
            BigInteger jBasicallyIntact = new BigInteger("0");
            BigInteger dBasicallyIntact = new BigInteger("0");
            BigInteger hBasicallyIntact = new BigInteger("0");


            if (squareMetreList.size() > 0) {
                for (HouDam squareMetre : squareMetreList) {
                    pmDestroy = BigInteger.valueOf(squareMetre.getDestroy());
                    pmSeriousDamage = BigInteger.valueOf(squareMetre.getSeriousDamage());
                    pmModerateDamage = BigInteger.valueOf(squareMetre.getModerateDamage());
                    pmMinorDamage = BigInteger.valueOf(squareMetre.getMinorDamage());
                    pmBasicallyIntact = BigInteger.valueOf(squareMetre.getBasicallyIntact());
                }
            }
            if (betweenList.size() > 0) {
                for (HouDam between : betweenList) {
                    jDestroy = BigInteger.valueOf(between.getDestroy());
                    jSeriousDamage = BigInteger.valueOf(between.getSeriousDamage());
                    jModerateDamage = BigInteger.valueOf(between.getModerateDamage());
                    jMinorDamage = BigInteger.valueOf(between.getMinorDamage());
                    jBasicallyIntact = BigInteger.valueOf(between.getBasicallyIntact());
                }
            }
            if (buildingList.size() > 0) {
                for (HouDam building : buildingList) {
                    dDestroy = BigInteger.valueOf(building.getDestroy());
                    dSeriousDamage = BigInteger.valueOf(building.getSeriousDamage());
                    dModerateDamage = BigInteger.valueOf(building.getModerateDamage());
                    dMinorDamage = BigInteger.valueOf(building.getMinorDamage());
                    dBasicallyIntact = BigInteger.valueOf(building.getBasicallyIntact());
                }
            }
            if (householdList.size() > 0) {
                for (HouDam household : householdList) {
                    hDestroy = BigInteger.valueOf(household.getDestroy());
                    hSeriousDamage = BigInteger.valueOf(household.getSeriousDamage());
                    hModerateDamage = BigInteger.valueOf(household.getModerateDamage());
                    hMinorDamage = BigInteger.valueOf(household.getMinorDamage());
                    hBasicallyIntact = BigInteger.valueOf(household.getBasicallyIntact());
                }
            }


            BigInteger destroyArea = pmDestroy.multiply(BigInteger.valueOf(params.getSquareMetre())).add(
                    jDestroy.multiply(BigInteger.valueOf(params.getBetween()))).add(
                    dDestroy.multiply(BigInteger.valueOf(params.getBuilding()))).add(
                    hDestroy.multiply(BigInteger.valueOf(params.getHousehold())));

            BigInteger seriousDamageArea = pmSeriousDamage.multiply(BigInteger.valueOf(params.getSquareMetre())).add(
                    jSeriousDamage.multiply(BigInteger.valueOf(params.getBetween()))).add(
                    dSeriousDamage.multiply(BigInteger.valueOf(params.getBuilding()))).add(
                    hSeriousDamage.multiply(BigInteger.valueOf(params.getHousehold())));

            BigInteger moderateDamageArea = pmModerateDamage.multiply(BigInteger.valueOf(params.getSquareMetre())).add(
                    jModerateDamage.multiply(BigInteger.valueOf(params.getBetween()))).add(
                    dModerateDamage.multiply(BigInteger.valueOf(params.getBuilding()))).add(
                    hModerateDamage.multiply(BigInteger.valueOf(params.getHousehold())));

            BigInteger minorDamageArea = pmMinorDamage.multiply(BigInteger.valueOf(params.getSquareMetre())).add(
                    jMinorDamage.multiply(BigInteger.valueOf(params.getBetween()))).add(
                    dMinorDamage.multiply(BigInteger.valueOf(params.getBuilding()))).add(
                    hMinorDamage.multiply(BigInteger.valueOf(params.getHousehold())));

            BigInteger basicallyIntactArea = pmBasicallyIntact.multiply(BigInteger.valueOf(params.getSquareMetre())).add(
                    jBasicallyIntact.multiply(BigInteger.valueOf(params.getBetween()))).add(
                    dBasicallyIntact.multiply(BigInteger.valueOf(params.getBuilding()))).add(
                    hBasicallyIntact.multiply(BigInteger.valueOf(params.getHousehold())));

            BigInteger totalArea = destroyArea.add(seriousDamageArea).add(moderateDamageArea).add(minorDamageArea).add(basicallyIntactArea);

            BigDecimal destroyAreaDec = new BigDecimal(destroyArea);
            BigDecimal seriousDamageAreaDec = new BigDecimal(seriousDamageArea);
            BigDecimal moderateDamageAreaDec = new BigDecimal(moderateDamageArea);
            BigDecimal minorDamageAreaDec = new BigDecimal(minorDamageArea);
            BigDecimal basicallyIntactAreaDec = new BigDecimal(basicallyIntactArea);

            BigDecimal totalAreaDec = new BigDecimal(totalArea);

            HouDamSta HouDamSta = new HouDamSta();
            HouDamSta.setId(UUIDGenerator.getUUID());
            HouDamSta.setXsphdId(params.getId());
            HouDamSta.setTotalArea(String.valueOf(totalArea));
            HouDamSta.setStructureType(preStrTypeList.get(i));

            if (!(destroyAreaDec.compareTo(BigDecimal.ZERO) == 0)) {
                BigDecimal destroyDivide = destroyAreaDec.divide(totalAreaDec, 2, RoundingMode.HALF_UP);
                BigDecimal destroyMultiply = destroyDivide.multiply(new BigDecimal(100));
                String destroyStr = String.valueOf(destroyMultiply);
                String destroyScale = destroyStr.substring(0, destroyStr.indexOf("."));
                HouDamSta.setDestroyArea(String.valueOf(destroyArea));
                HouDamSta.setDestroyScale(destroyScale + "%");
            } else {
                HouDamSta.setDestroyArea(String.valueOf(destroyArea));
                HouDamSta.setDestroyScale(destroyArea + "%");
            }

            if (!(seriousDamageAreaDec.compareTo(BigDecimal.ZERO) == 0)) {
                BigDecimal seriousDamageDivide = seriousDamageAreaDec.divide(totalAreaDec, 2, RoundingMode.HALF_UP);
                BigDecimal seriousDamageMultiply = seriousDamageDivide.multiply(new BigDecimal(100));
                String seriousDamageStr = String.valueOf(seriousDamageMultiply);
                String seriousDamageScale = seriousDamageStr.substring(0, seriousDamageStr.indexOf("."));
                HouDamSta.setSeriousDamageArea(String.valueOf(seriousDamageArea));
                HouDamSta.setSeriousDamageScale(seriousDamageScale + "%");
            } else {
                HouDamSta.setSeriousDamageArea(String.valueOf(seriousDamageArea));
                HouDamSta.setSeriousDamageScale(seriousDamageArea + "%");
            }

            if (!(moderateDamageAreaDec.compareTo(BigDecimal.ZERO) == 0)) {
                BigDecimal moderateDamageDivide = moderateDamageAreaDec.divide(totalAreaDec, 2, RoundingMode.HALF_UP);
                BigDecimal moderateDamageMultiply = moderateDamageDivide.multiply(new BigDecimal(100));
                String moderateDamageStr = String.valueOf(moderateDamageMultiply);
                String moderateDamageScale = moderateDamageStr.substring(0, moderateDamageStr.indexOf("."));
                HouDamSta.setModerateDamageArea(String.valueOf(moderateDamageArea));
                HouDamSta.setModerateDamageScale(moderateDamageScale + "%");
            } else {
                HouDamSta.setModerateDamageArea(String.valueOf(moderateDamageArea));
                HouDamSta.setModerateDamageScale(moderateDamageArea + "%");
            }

            if (!(minorDamageAreaDec.compareTo(BigDecimal.ZERO) == 0)) {
                BigDecimal minorDamageDivide = minorDamageAreaDec.divide(totalAreaDec, 2, RoundingMode.HALF_UP);
                BigDecimal minorDamageMultiply = minorDamageDivide.multiply(new BigDecimal(100));
                String minorDamageStr = String.valueOf(minorDamageMultiply);
                String minorDamageScale = minorDamageStr.substring(0, minorDamageStr.indexOf("."));
                HouDamSta.setMinorDamageArea(String.valueOf(minorDamageArea));
                HouDamSta.setMinorDamageScale(minorDamageScale + "%");
            } else {
                HouDamSta.setMinorDamageArea(String.valueOf(minorDamageArea));
                HouDamSta.setMinorDamageScale(minorDamageArea + "%");
            }

            if (!(minorDamageAreaDec.compareTo(BigDecimal.ZERO) == 0)) {
                BigDecimal basicallyIntactDivide = basicallyIntactAreaDec.divide(totalAreaDec, 2, RoundingMode.HALF_UP);
                BigDecimal basicallyIntactMultiply = basicallyIntactDivide.multiply(new BigDecimal(100));
                String basicallyIntactStr = String.valueOf(basicallyIntactMultiply);
                String basicallyIntactScale = basicallyIntactStr.substring(0, basicallyIntactStr.indexOf("."));
                HouDamSta.setBasicallyIntactArea(String.valueOf(basicallyIntactArea));
                HouDamSta.setBasicallyIntactScale(basicallyIntactScale + "%");
            } else {
                HouDamSta.setBasicallyIntactArea(String.valueOf(basicallyIntactArea));
                HouDamSta.setBasicallyIntactScale(basicallyIntactArea + "%");
            }
            houDamStaRepository.save(HouDamSta);
            //returnList.add(HouDamSta);
            list.clear();
        }


        //return returnList;
    }

    @Override
    public List<HouDamSta> getStaResult(String id) {

        return houDamStaRepository.getStaResult(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void check(List<SamPoiHouSurParam> list) {
        ArrayList<AuditNotice> AuditList = new ArrayList<>();
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        for (SamPoiHouSurParam samPoiHouSur : list) {
            samPoliHouSurRepository.check(samPoiHouSur.getId(), samPoiHouSur.getCheckStatus(), samPoiHouSur.getCheckOpinion());
            if ("3".equals(samPoiHouSur.getCheckStatus())) {
                AuditNotice auditNotice = getAuditNotice(samPoiHouSur, sUser);
                AuditList.add(auditNotice);
            }
        }
        if (list.size() > 0) {
            String s = noticeService.auditNotice(AuditList);
        }
    }

    //转换实体
    public AuditNotice getAuditNotice(SamPoiHouSurParam samPoiHouSur, SUser sUser) {
        AuditNotice auditNotice = new AuditNotice();
        auditNotice.setXnmId(UUID.randomUUID().toString().replaceAll("-", ""));
        auditNotice.setDelFlag(YNEnum.N.toString());
        auditNotice.setCreateUser(sUser.getUserId());
        auditNotice.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        auditNotice.setXsemId(samPoiHouSur.getXsemId());
        //通知类型
        auditNotice.setNoticeType("1");
        //通知名称
        auditNotice.setNoticeName("【" + samPoiHouSur.getSamplingPointHouseCode() + "】的抽样点房屋调查数据审核未通过");
        //通知内容
        auditNotice.setNoticeContent("数据编号为【" + samPoiHouSur.getSamplingPointHouseCode() + "】的抽样点房屋调查数据审核未通过,未通过原因【" + samPoiHouSur.getCheckOpinion() + "】");
        //发起人
        auditNotice.setSponsor(sUser.getUserName());
        //通知时间
        auditNotice.setNoticeTime(auditNotice.getCreateTime());
        //通知范围
        auditNotice.setNoticeRange(samPoiHouSur.getCreateUserName());
        //被通知人id
        auditNotice.setBeNotified(samPoiHouSur.getCreateUser());
        return auditNotice;
    }

    @Override
    public void update(SamPoiHouSur samPoiHouSur) {
        samPoiHouSur.setUpdateTime(new Date());
        samPoiHouSur.setUpdateUser(PlatformSessionContext.getUserID());
        samPoliHouSurRepository.update(samPoiHouSur);
    }

    @Override
    public void checkExportExcel(HttpServletResponse response, SamPoiHouSurQuaParams queParams) {
        List<SamPoiHouSurCheckVo> list = samPoliHouSurRepository.getSamPoiCheckDataList(queParams);
        if (list.size() <= 0) {
            throw new RuntimeException("数据为空,无法导出！");
        }
        for (SamPoiHouSurCheckVo item : list) {
            if (!PlatformObjectUtils.isEmpty(item.getMacroscopicAnomaly())) {
                StringBuilder macroscopicAnomaly = new StringBuilder("");
                for (int a = 0; a < item.getMacroscopicAnomaly().split(",").length; a++) {
                    macroscopicAnomaly.append(macroscopicAnomaly(item.getMacroscopicAnomaly().split(",")[a])).append("、");
                }
                item.setMacroscopicAnomaly(macroscopicAnomaly.substring(0, macroscopicAnomaly.length() - 1).toString());
            }
            if (!PlatformObjectUtils.isEmpty(item.getGeologicHazard())) {
                StringBuilder geologicHazard = new StringBuilder("");
                for (int a = 0; a < item.getGeologicHazard().split(",").length; a++) {
                    geologicHazard.append(geologicHazard(item.getGeologicHazard().split(",")[a])).append(",").append("、");
                }
                item.setGeologicHazard(geologicHazard.substring(0, geologicHazard.length() - 1).toString());
            }
            if (!PlatformObjectUtils.isEmpty(item.getBuildingEarthquakeDescription())) {
                StringBuilder buildingEarthquakeDescription = new StringBuilder("");
                for (int a = 0; a < item.getBuildingEarthquakeDescription().split(",").length; a++) {
                    buildingEarthquakeDescription.append(buildingEarthquakeDescription(item.getBuildingEarthquakeDescription().split(",")[a])).append("、");
                }
                item.setBuildingEarthquakeDescription(buildingEarthquakeDescription.substring(0, buildingEarthquakeDescription.length() - 1).toString());
            }
        }
        try {
            EasyPoiExcelUtil.exportExcel(list, "抽样点房屋数据信息统计", "抽样点房屋数据信息", SamPoiHouSurCheckVo.class, "抽样点房屋数据信息", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 宏观异常现象
     *
     * @param type
     * @return
     */
    private String macroscopicAnomaly(String type) {
        if (FxfzConstants.DXSYC.equals(type)) {
            type = "地下水异常";
        }
        if (FxfzConstants.SWYC.equals(type)) {
            type = "生物异常";
        }
        if (FxfzConstants.QXYC.equals(type)) {
            type = "气象异常";
        }
        if (FxfzConstants.DSYC.equals(type)) {
            type = "地声异常";
        }
        if (FxfzConstants.DGYC.equals(type)) {
            type = "地光异常";
        }
        if (FxfzConstants.DQYC.equals(type)) {
            type = "地气异常";
        }
        if (FxfzConstants.DDYC.equals(type)) {
            type = "地动异常";
        }
        if (FxfzConstants.DGUYC.equals(type)) {
            type = "地鼓异常";
        }
        if (FxfzConstants.DCYC.equals(type)) {
            type = "电磁异常";
        }
        if (FxfzConstants.WYC.equals(type)) {
            type = "无异常";
        }
        return type;
    }

    /**
     * 地质灾害
     *
     * @param type
     * @return
     */
    private String geologicHazard(String type) {
        if (FxfzConstants.DBPL.equals(type)) {
            type = "地表破裂";
        }
        if (FxfzConstants.DLF.equals(type)) {
            type = "地裂缝";
        }
        if (FxfzConstants.BT.equals(type)) {
            type = "崩塌";
        }
        if (FxfzConstants.HP.equals(type)) {
            type = "滑坡";
        }
        if (FxfzConstants.NSL.equals(type)) {
            type = "泥石流";
        }
        if (FxfzConstants.STYH.equals(type)) {
            type = "砂土液化";
        }
        if (FxfzConstants.RTZX.equals(type)) {
            type = "软土震陷";
        }
        if (FxfzConstants.QT.equals(type)) {
            type = "其他";
        }
        return type;
    }

    /**
     * 建筑物震害特征描述
     *
     * @param type
     * @return
     */
    private String buildingEarthquakeDescription(String type) {
        if (FxfzConstants.QWFD.equals(type)) {
            type = "器物翻倒";
        }
        if (FxfzConstants.ZYCDL.equals(type)) {
            type = "砖烟囱断裂";
        }
        if (FxfzConstants.GBFWJBDT.equals(type)) {
            type = "个别房屋局部倒塌";
        }
        if (FxfzConstants.SSFWDT.equals(type)) {
            type = "少数房屋倒塌";
        }
        if (FxfzConstants.DSFWDT.equals(type)) {
            type = "多数房屋倒塌";
        }
        if (FxfzConstants.FWPBDT.equals(type)) {
            type = "房屋普遍倒塌";
        }
        if (FxfzConstants.SHGG.equals(type)) {
            type = "山河改观";
        }
        return type;
    }

    @Override
    public void isDamnificationCount(String id, String state) {
        samPoliHouSurRepository.isDamnificationCount(id, state);
    }

    @Override
    public List<SamPoiHouSur> getTaskListByXsemId(String xsemId) {
        return samPoliHouSurRepository.getTaskListByXsemId(xsemId);
    }

    @Override
    public SamPoiHouSur getTaskListByXspdId(String xspdId) {
        return samPoliHouSurRepository.getTaskListByXspdId(xspdId);
    }

    @Override
    @Transactional
    public Map<String, Object> importExcel(MultipartFile file, String xsemId) {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(2);
        //params.setImportFields(new String[]{"省","市","区(县)","详细地址","抽样点名称","房屋单体名称","经度","纬度","结构类型","破坏情况","建筑面积（平方米）","用途类型","是否为典型房屋","损失值（元）","室内外财产损失比例","是否为中高档装修","具体描述情况"});
        params.setNeedVerify(true);
        params.setVerifyHandler(samPoiHouSurExcelVerifyHandler);
        boolean res = false;
        Map<String, Object> map = new HashMap<>();
        try {
            String userId = PlatformSessionContext.getUserID();
            String user = sUserService.getSUser(userId);
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            String userName = sUser.getUserName();
            EarEveManage currentEvent = earEveManageService.getCurrentEvent();//获取当前地震事件
            InputStream inputStream = file.getInputStream();
            ExcelImportResult<SamPoiHouSurExcelVo> result = ExcelImportUtil.importExcelMore(inputStream, SamPoiHouSurExcelVo.class, params);
            List<SamPoiHouSurExcelVo> failList = result.getFailList();
            if (PlatformObjectUtils.isNotEmpty(failList)) {
                StringBuilder errorMsg = new StringBuilder("<font size='5px' color='red'>导入失败：</font>");
                for (SamPoiHouSurExcelVo samPoiHouSurExcelVo : failList) {
                    errorMsg.append("<font size='4px' ><br>").append("第").append(samPoiHouSurExcelVo.getRowNum() + 1).append("行： ").append(samPoiHouSurExcelVo.getErrorMsg()).append("</font>");
                }
                map.put("res", res);
                map.put("mess", errorMsg);
                return map;
            }
            List<SamPoiHouSurExcelVo> resultData = result.getList();//解析excel
            if (!PlatformObjectUtils.isEmpty(resultData)) {
                //SamPoiHouSurExcelVo samPoiHouSurExcelVo = resultData.get(0);//只导入一条数据,抽样点房屋和抽样点是1对1的关系
                for(SamPoiHouSurExcelVo samPoiHouSurExcelVo:resultData){
                    SamPoiHouSur samPoiHouSur = new SamPoiHouSur();
                    SpringUtil.copyPropertiesIgnoreNull(samPoiHouSurExcelVo, samPoiHouSur);
                    //空间数据
                    samPoiHouSur.setGeom("POINT("+samPoiHouSur.getLongitude()+" " +samPoiHouSur.getLatitude()+")");
                    String uuid = UUIDGenerator.getUUID();
                    /*samPoiHouSur.getSamplingPointName()*/
                    List<SamPoiData> list=samPoiDataService.findBySamplingPointName(samPoiHouSur.getSamplingPointName(),xsemId);
                    if(list.size()>0){
                        //如果查出多个取第一个
                        SamPoiData samPoiData = list.get(0);

                        samPoiHouSur.setId(uuid);
                        samPoiHouSur.setXsemId(xsemId);
                        samPoiHouSur.setXspdId(samPoiData.getId());
                        samPoiHouSur.setSamplingPointName(samPoiData.getSamplingPointName());
                        samPoiHouSur.setType(samPoiData.getType());
                        samPoiHouSur.setIsDamnificationCount("1");
                        //生成 抽样点房屋编号
                        String samplingPointHouseCode = getsamPoiHouCode(currentEvent.getEventCode());
                        samPoiHouSur.setSamplingPointHouseCode(samplingPointHouseCode);

                        //地形地貌
                        String topographicFeatures = dictService.getKeyByDictCodeAndValue("dxdm", samPoiHouSurExcelVo.getTopographicFeatures());
                        samPoiHouSur.setTopographicFeatures(topographicFeatures);

                        //人员震感情况
                        String personnelShock = dictService.getKeyByDictCodeAndValue("ryzgqk", samPoiHouSurExcelVo.getPersonnelShock());
                        samPoiHouSur.setPersonnelShock(personnelShock);

                        //器皿反应情况
                        String reactionOfVessels = dictService.getKeyByDictCodeAndValue("qmfyqk", samPoiHouSurExcelVo.getReactionOfVessels());
                        samPoiHouSur.setReactionOfVessels(reactionOfVessels);

                        //烈度拟定
                        //String intensityDetermination = dictService.getKeyByDictCodeAndValue("ldnd", samPoiHouSurExcelVo.getIntensityDetermination());//从数据字典中获取key
                        String intensityDetermination = intensityMap().get(samPoiHouSurExcelVo.getIntensityDetermination());
                        samPoiHouSur.setIntensityDetermination(intensityDetermination);

                        //宏观异常现象
                        String macroscopicAnomaly2 = "";
                        String macroscopicAnomaly = samPoiHouSurExcelVo.getMacroscopicAnomaly();
                        if (PlatformObjectUtils.isNotEmpty(macroscopicAnomaly)) {
                            for (String str : macroscopicAnomaly.split("、")) {
                                macroscopicAnomaly2 += dictService.getKeyByDictCodeAndValue("hgycxx", str) + ",";//从数据字典中获取key
                            }
                            macroscopicAnomaly2 = macroscopicAnomaly2.substring(0, macroscopicAnomaly2.length() - 1);
                            samPoiHouSur.setMacroscopicAnomaly(macroscopicAnomaly2);
                        }


                        //地质灾害
                        String geologicHazard2 = "";
                        String geologicHazard = samPoiHouSurExcelVo.getGeologicHazard();
                        if (PlatformObjectUtils.isNotEmpty(geologicHazard)) {
                            for (String str : geologicHazard.split("、")) {
                                geologicHazard2 += dictService.getKeyByDictCodeAndValue("dzzh", str) + ",";//从数据字典中获取key
                            }
                            geologicHazard2 = geologicHazard2.substring(0, geologicHazard2.length() - 1);
                            samPoiHouSur.setGeologicHazard(geologicHazard2);
                        }


                        //建筑物震害特征描述
                        String buildingEarthquakeDescription2 = "";
                        String buildingEarthquakeDescription = samPoiHouSurExcelVo.getBuildingEarthquakeDescription();
                        if (PlatformObjectUtils.isNotEmpty(buildingEarthquakeDescription)) {
                            for (String str : buildingEarthquakeDescription.split("、")) {
                                buildingEarthquakeDescription2 += dictService.getKeyByDictCodeAndValue("jzwzhtzms", str) + ",";//从数据字典中获取key
                            }
                            buildingEarthquakeDescription2 = buildingEarthquakeDescription2.substring(0, buildingEarthquakeDescription2.length() - 1);
                            samPoiHouSur.setBuildingEarthquakeDescription(buildingEarthquakeDescription2);
                        }
                        samPoiHouSur.setCheckStatus("2");
                        samPoiHouSur.setDelFlag(YNEnum.N.toString());
                        samPoiHouSur.setCreateTime(new Date());
                        samPoiHouSur.setCreateUser(userId);
                        samPoiHouSur.setCreateUserName(userName);
                        res = samPoliHouSurRepository.save(samPoiHouSur);

                        //保存计算结果
                        //I类
                        CalculateParams calculateParams = new CalculateParams();
                        calculateParams.setDestroyArea(samPoiHouSurExcelVo.getDestroy());
                        calculateParams.setSeriousDamageArea(samPoiHouSurExcelVo.getSeriousDamage());
                        calculateParams.setModerateDamageArea(samPoiHouSurExcelVo.getModerateDamage());
                        calculateParams.setMinorDamageArea(samPoiHouSurExcelVo.getMinorDamage());
                        calculateParams.setBasicallyIntactArea(samPoiHouSurExcelVo.getBasicallyIntact());
                        calculateParams.setStructureType(XczhConstants.ONE_TYPE);
                        calculateParams.setXsphdId(uuid);
                        //II类
                        CalculateParams calculateParams1 = new CalculateParams();
                        calculateParams1.setDestroyArea(samPoiHouSurExcelVo.getDestroy1());
                        calculateParams1.setSeriousDamageArea(samPoiHouSurExcelVo.getSeriousDamage1());
                        calculateParams1.setModerateDamageArea(samPoiHouSurExcelVo.getModerateDamage1());
                        calculateParams1.setMinorDamageArea(samPoiHouSurExcelVo.getMinorDamage1());
                        calculateParams1.setBasicallyIntactArea(samPoiHouSurExcelVo.getBasicallyIntact1());
                        calculateParams1.setStructureType(XczhConstants.TWO_TYPE);
                        calculateParams1.setXsphdId(uuid);
                        //III-1类
                        CalculateParams calculateParams2 = new CalculateParams();
                        calculateParams2.setDestroyArea(samPoiHouSurExcelVo.getDestroy2());
                        calculateParams2.setSeriousDamageArea(samPoiHouSurExcelVo.getSeriousDamage2());
                        calculateParams2.setModerateDamageArea(samPoiHouSurExcelVo.getModerateDamage2());
                        calculateParams2.setMinorDamageArea(samPoiHouSurExcelVo.getMinorDamage2());
                        calculateParams2.setBasicallyIntactArea(samPoiHouSurExcelVo.getBasicallyIntact2());
                        calculateParams2.setStructureType(XczhConstants.THREE_ONE_TYPE);
                        calculateParams2.setXsphdId(uuid);
                        //III-2类
                        CalculateParams calculateParams3 = new CalculateParams();
                        calculateParams3.setDestroyArea(samPoiHouSurExcelVo.getDestroy3());
                        calculateParams3.setSeriousDamageArea(samPoiHouSurExcelVo.getSeriousDamage3());
                        calculateParams3.setModerateDamageArea(samPoiHouSurExcelVo.getModerateDamage3());
                        calculateParams3.setMinorDamageArea(samPoiHouSurExcelVo.getMinorDamage3());
                        calculateParams3.setBasicallyIntactArea(samPoiHouSurExcelVo.getBasicallyIntact3());
                        calculateParams3.setStructureType(XczhConstants.THREE_TWO_TYPE);
                        calculateParams3.setXsphdId(uuid);
                        //Ⅳ类
                        CalculateParams calculateParams4 = new CalculateParams();
                        calculateParams4.setDestroyArea(samPoiHouSurExcelVo.getDestroy4());
                        calculateParams4.setSeriousDamageArea(samPoiHouSurExcelVo.getSeriousDamage4());
                        calculateParams4.setModerateDamageArea(samPoiHouSurExcelVo.getModerateDamage4());
                        calculateParams4.setMinorDamageArea(samPoiHouSurExcelVo.getMinorDamage4());
                        calculateParams4.setBasicallyIntactArea(samPoiHouSurExcelVo.getBasicallyIntact4());
                        calculateParams4.setStructureType(XczhConstants.FOUR_TYPE);
                        calculateParams4.setXsphdId(uuid);
                        //V-1类
                        CalculateParams calculateParams5 = new CalculateParams();
                        calculateParams5.setDestroyArea(samPoiHouSurExcelVo.getDestroy5());
                        calculateParams5.setSeriousDamageArea(samPoiHouSurExcelVo.getSeriousDamage5());
                        calculateParams5.setModerateDamageArea(samPoiHouSurExcelVo.getModerateDamage5());
                        calculateParams5.setMinorDamageArea(samPoiHouSurExcelVo.getMinorDamage5());
                        calculateParams5.setBasicallyIntactArea(samPoiHouSurExcelVo.getBasicallyIntact5());
                        calculateParams5.setStructureType(XczhConstants.FIVE_ONE_TYPE);
                        calculateParams5.setXsphdId(uuid);
                        //V-2类
                        CalculateParams calculateParams6 = new CalculateParams();
                        calculateParams6.setDestroyArea(samPoiHouSurExcelVo.getDestroy6());
                        calculateParams6.setSeriousDamageArea(samPoiHouSurExcelVo.getSeriousDamage6());
                        calculateParams6.setModerateDamageArea(samPoiHouSurExcelVo.getModerateDamage6());
                        calculateParams6.setMinorDamageArea(samPoiHouSurExcelVo.getMinorDamage6());
                        calculateParams6.setBasicallyIntactArea(samPoiHouSurExcelVo.getBasicallyIntact6());
                        calculateParams6.setStructureType(XczhConstants.FIVE_TWO_TYPE);
                        calculateParams6.setXsphdId(uuid);
                        //V-3类
                        CalculateParams calculateParams7 = new CalculateParams();
                        calculateParams7.setDestroyArea(samPoiHouSurExcelVo.getDestroy7());
                        calculateParams7.setSeriousDamageArea(samPoiHouSurExcelVo.getSeriousDamage7());
                        calculateParams7.setModerateDamageArea(samPoiHouSurExcelVo.getModerateDamage7());
                        calculateParams7.setMinorDamageArea(samPoiHouSurExcelVo.getMinorDamage7());
                        calculateParams7.setBasicallyIntactArea(samPoiHouSurExcelVo.getBasicallyIntact7());
                        calculateParams7.setStructureType(XczhConstants.FIVE_THREE_TYPE);
                        calculateParams7.setXsphdId(uuid);
                        //Ⅵ类
                        CalculateParams calculateParams8 = new CalculateParams();
                        calculateParams8.setDestroyArea(samPoiHouSurExcelVo.getDestroy8());
                        calculateParams8.setSeriousDamageArea(samPoiHouSurExcelVo.getSeriousDamage8());
                        calculateParams8.setModerateDamageArea(samPoiHouSurExcelVo.getModerateDamage8());
                        calculateParams8.setMinorDamageArea(samPoiHouSurExcelVo.getMinorDamage8());
                        calculateParams8.setBasicallyIntactArea(samPoiHouSurExcelVo.getBasicallyIntact8());
                        calculateParams8.setBasicallyIntactArea(samPoiHouSurExcelVo.getBasicallyIntact8());
                        calculateParams8.setStructureType(XczhConstants.SIX_TYPE);
                        calculateParams8.setXsphdId(uuid);
                        //Ⅶ类
                        CalculateParams calculateParams9 = new CalculateParams();
                        calculateParams9.setDestroyArea(samPoiHouSurExcelVo.getDestroy9());
                        calculateParams9.setSeriousDamageArea(samPoiHouSurExcelVo.getSeriousDamage9());
                        calculateParams9.setModerateDamageArea(samPoiHouSurExcelVo.getModerateDamage9());
                        calculateParams9.setMinorDamageArea(samPoiHouSurExcelVo.getMinorDamage9());
                        calculateParams9.setBasicallyIntactArea(samPoiHouSurExcelVo.getBasicallyIntact9());
                        calculateParams9.setStructureType(XczhConstants.SEVEN_TYPE);
                        calculateParams9.setXsphdId(uuid);

                        resultSave(calculateParams);
                        resultSave(calculateParams1);
                        resultSave(calculateParams2);
                        resultSave(calculateParams3);
                        resultSave(calculateParams4);
                        resultSave(calculateParams5);
                        resultSave(calculateParams6);
                        resultSave(calculateParams7);
                        resultSave(calculateParams8);
                        resultSave(calculateParams9);


                        //保存专门维护省市区县的表
                        ReportPublicField reportPublicField = new ReportPublicField();
                        reportPublicField.setXlrmId(uuid);
                        reportPublicField.setXsemId(xsemId);
                        reportPublicField.setProvince(samPoiHouSurExcelVo.getProvince());
                        reportPublicField.setCity(samPoiHouSurExcelVo.getCity());
                        reportPublicField.setCounty(samPoiHouSurExcelVo.getArea());
                        reportPublicField.setCreateUser(userId);
                        reportPublicField.setDelFlag("0");
                        reportPublicFieldRepository.save(reportPublicField);
                    }else{
                        StringBuilder errorMsg = new StringBuilder("<font size='5px' color='red'>导入失败：</font>");
                        errorMsg.append("<font size='4px' ><br>").append("第").append(samPoiHouSurExcelVo.getRowNum() + 1).append("行： ").append("未匹配到对应抽样点").append("</font>");
                        map.put("res", res);
                        map.put("mess", errorMsg);
                        return map;
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("res", res);
        return map;
    }

    private Map<String,String> intensityMap(){
        Map<String,String> map = new HashMap<>();
        map.put("VI度","6");
        map.put("VII度","7");
        map.put("VIII度","8");
        map.put("IX度","9");
        map.put("X度","10");
        map.put("XI度","11");
        map.put("XII度","12");
        return map;
    }
    public void resultSave(CalculateParams params) {
        //houDamStaRepository.delete(params.getId());
        BigDecimal destroyArea = new BigDecimal("0");
        BigDecimal seriousDamageArea = new BigDecimal("0");
        BigDecimal moderateDamageArea = new BigDecimal("0");
        BigDecimal minorDamageArea = new BigDecimal("0");
        BigDecimal basicallyIntactArea = new BigDecimal("0");
        //毁 面积
        if (PlatformObjectUtils.isNotEmpty(params.getDestroyArea())) {
            destroyArea = new BigDecimal(String.valueOf(params.getDestroyArea()));
        }
        //严 面积

        if (PlatformObjectUtils.isNotEmpty(params.getSeriousDamageArea())) {
            seriousDamageArea = new BigDecimal(String.valueOf(params.getSeriousDamageArea()));
        }
        //中 面积
        if (PlatformObjectUtils.isNotEmpty(params.getModerateDamageArea())) {
            moderateDamageArea = new BigDecimal(String.valueOf(params.getModerateDamageArea()));
        }
        //轻 面积
        if (PlatformObjectUtils.isNotEmpty(params.getMinorDamageArea())) {
            minorDamageArea = new BigDecimal(String.valueOf(params.getMinorDamageArea()));
        }
        //好 面积
        if (PlatformObjectUtils.isNotEmpty(params.getBasicallyIntactArea())) {
            basicallyIntactArea = new BigDecimal(String.valueOf(params.getBasicallyIntactArea()));
        }

        //计算总面积
        BigDecimal totalArea = destroyArea.add(seriousDamageArea).add(moderateDamageArea).add(minorDamageArea).add(basicallyIntactArea);


        HouDamSta houDamSta = new HouDamSta();
        houDamSta.setId(UUIDGenerator.getUUID());
        houDamSta.setXsphdId(params.getXsphdId());
        houDamSta.setTotalArea(String.valueOf(totalArea));
        houDamSta.setStructureType(params.getStructureType());

        //毁 指数
        BigDecimal destroyIndex = new BigDecimal("0");
        //严 指数
        BigDecimal seriousDamageIndex = new BigDecimal("0");
        //中 指数
        BigDecimal moderateDamageIndex = new BigDecimal("0");
        //轻 指数
        BigDecimal minorDamageIndex = new BigDecimal("0");
        //好 指数
        BigDecimal basicallyIntactIndex = new BigDecimal("0");

        //计算比率
        if (!(destroyArea.compareTo(BigDecimal.ZERO) == 0)) {
            BigDecimal destroyDivide = destroyArea.divide(totalArea, 2, RoundingMode.HALF_UP);
            BigDecimal destroyMultiply = destroyDivide.multiply(new BigDecimal(100));
            String destroyStr = String.valueOf(destroyMultiply);
            String destroyScale = destroyStr.substring(0, destroyStr.indexOf("."));
            houDamSta.setDestroyArea(String.valueOf(destroyArea));
            houDamSta.setDestroyScale(destroyScale);
            destroyIndex=destroyDivide;
            //destroyIndex=new BigDecimal(destroyScale).divide(new BigDecimal(DesDegConstants.DESTROY_INDEX));
        } else {
            houDamSta.setDestroyArea(String.valueOf(destroyArea));
            houDamSta.setDestroyScale(destroyArea + "");
        }

        if (!(seriousDamageArea.compareTo(BigDecimal.ZERO) == 0)) {
            BigDecimal seriousDamageDivide = seriousDamageArea.divide(totalArea, 2, RoundingMode.HALF_UP);
            BigDecimal seriousDamageMultiply = seriousDamageDivide.multiply(new BigDecimal(100));
            String seriousDamageStr = String.valueOf(seriousDamageMultiply);
            String seriousDamageScale = seriousDamageStr.substring(0, seriousDamageStr.indexOf("."));
            houDamSta.setSeriousDamageArea(String.valueOf(seriousDamageArea));
            houDamSta.setSeriousDamageScale(seriousDamageScale);
            seriousDamageIndex = seriousDamageDivide.multiply(new BigDecimal(DesDegConstants.SERIOUS_DAMAGE_INDEX)).setScale(2,BigDecimal.ROUND_HALF_UP);
        } else {
            houDamSta.setSeriousDamageArea(String.valueOf(seriousDamageArea));
            houDamSta.setSeriousDamageScale(seriousDamageArea + "");
        }

        if (!(moderateDamageArea.compareTo(BigDecimal.ZERO) == 0)) {
            BigDecimal moderateDamageDivide = moderateDamageArea.divide(totalArea, 2, RoundingMode.HALF_UP);
            BigDecimal moderateDamageMultiply = moderateDamageDivide.multiply(new BigDecimal(100));
            String moderateDamageStr = String.valueOf(moderateDamageMultiply);
            String moderateDamageScale = moderateDamageStr.substring(0, moderateDamageStr.indexOf("."));
            houDamSta.setModerateDamageArea(String.valueOf(moderateDamageArea));
            houDamSta.setModerateDamageScale(moderateDamageScale);
            moderateDamageIndex = moderateDamageDivide.multiply(new BigDecimal(DesDegConstants.MODERATE_DAMAGE_INDEX)).setScale(2,BigDecimal.ROUND_HALF_UP);
        } else {
            houDamSta.setModerateDamageArea(String.valueOf(moderateDamageArea));
            houDamSta.setModerateDamageScale(moderateDamageArea + "");
        }

        if (!(minorDamageArea.compareTo(BigDecimal.ZERO) == 0)) {
            BigDecimal minorDamageDivide = minorDamageArea.divide(totalArea, 2, RoundingMode.HALF_UP);
            BigDecimal minorDamageMultiply = minorDamageDivide.multiply(new BigDecimal(100));
            String minorDamageStr = String.valueOf(minorDamageMultiply);
            String minorDamageScale = minorDamageStr.substring(0, minorDamageStr.indexOf("."));
            houDamSta.setMinorDamageArea(String.valueOf(minorDamageArea));
            houDamSta.setMinorDamageScale(minorDamageScale);
            minorDamageIndex = minorDamageDivide.multiply(new BigDecimal(DesDegConstants.MINOR_DAMAGE_INDEX)).setScale(2,BigDecimal.ROUND_HALF_UP);
        } else {
            houDamSta.setMinorDamageArea(String.valueOf(minorDamageArea));
            houDamSta.setMinorDamageScale(minorDamageArea + "");
        }

        if (!(basicallyIntactArea.compareTo(BigDecimal.ZERO) == 0)) {
            BigDecimal basicallyIntactDivide = basicallyIntactArea.divide(totalArea, 2, RoundingMode.HALF_UP);
            BigDecimal basicallyIntactMultiply = basicallyIntactDivide.multiply(new BigDecimal(100));
            String basicallyIntactStr = String.valueOf(basicallyIntactMultiply);
            String basicallyIntactScale = basicallyIntactStr.substring(0, basicallyIntactStr.indexOf("."));
            houDamSta.setBasicallyIntactArea(String.valueOf(basicallyIntactArea));
            houDamSta.setBasicallyIntactScale(basicallyIntactScale);
            basicallyIntactIndex = basicallyIntactDivide.multiply(new BigDecimal(DesDegConstants.BASICALLY_INTACT_INDEX));
        } else {
            houDamSta.setBasicallyIntactArea(String.valueOf(basicallyIntactArea));
            houDamSta.setBasicallyIntactScale(basicallyIntactArea + "");
        }

        //计算震害指数
        BigDecimal damageIndex = destroyIndex.add(seriousDamageIndex).add(moderateDamageIndex).add(minorDamageIndex).add(basicallyIntactIndex).setScale(2,BigDecimal.ROUND_HALF_UP);;
        houDamSta.setDamageIndex(damageIndex + "");
        houDamStaRepository.save(houDamSta);
    }

    @Override
    public void submit(String ids) {
        String[] split = ids.split(",");
        for (String id : split) {
            samPoliHouSurRepository.submit(id);
        }

    }

    @Override
    public void delete(String ids) {
        samPoliHouSurRepository.delete(ids.split(","));
    }

    @Override
    public Map<String, Object> getAppPage(SamPoiHouSurQuaParams queParams, int curPage, int pageSize) {
        Map<String, Object> page = samPoliHouSurRepository.getAppPage(queParams, curPage, pageSize);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateApp(SamPoiHouSur samPoiHouSur) {
            samPoiHouSur.setUpdateTime(new Date());
            samPoiHouSur.setUpdateUser(PlatformSessionContext.getUserID());
        if (PlatformObjectUtils.isNotEmpty(samPoiHouSur.getHouseDamage())){
                for (HouDam houDam : samPoiHouSur.getHouseDamage()) {
                    houseDamageRepository.updateById(houDam);
                }
            }

            //修改统计结果
            List<HouDamSta> statisticsResult = samPoiHouSur.getStatisticsResult();
            if (PlatformObjectUtils.isNotEmpty(statisticsResult)){
                if (statisticsResult.size() > 0) {
                    for (HouDamSta item : statisticsResult) {
                        houDamStaRepository.updateById(item);
                    }
                }
            }
            samPoliHouSurRepository.update(samPoiHouSur);
    }

    @Override
    public List<SamPoiHouSur> getSamPoiHouDataByXsemIdAndType(String xsemId, String type,String checkStatus) {
        return samPoliHouSurRepository.getSamPoiHouDataByXsemIdAndType(xsemId,type,checkStatus);
    }


}
